package com.udaos.modules.school.controllers;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.By;
import org.nutz.mvc.annotation.Filters;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

import com.udaos.common.annotation.SLog;
import com.udaos.common.base.Result;
import com.udaos.common.filter.PrivateFilter;
import com.udaos.common.page.DataTableColumn;
import com.udaos.common.page.DataTableOrder;
import com.udaos.common.util.StringUtil;
import com.udaos.models.area.Ud_area;
import com.udaos.models.region.Ud_region;
import com.udaos.models.school.Ud_school;
import com.udaos.models.school.Ud_school_area;
import com.udaos.models.sys.Sys_user;
import com.udaos.modules.area.services.UdAreaService;
import com.udaos.modules.region.services.UdRegionService;
import com.udaos.modules.school.services.UdSchoolAreaService;
import com.udaos.modules.school.services.UdSchoolService;


/**
 * 驾校管理
 * @author 穆涛涛
 * 
 */
@IocBean
@At("/platform/school")
@Filters({ @By(type = PrivateFilter.class)})
public class UdSchoolController {
	@Inject
	private UdSchoolService schoolService;
	@Inject
	private UdAreaService areaService;
	@Inject
	private UdSchoolAreaService schoolAreaService;
	@Inject
	private UdRegionService regionService;

	/**
	 * 首页
	 */
	@At("")
	@Ok("beetl:/platform/base/school/index.html")
	@RequiresAuthentication
	public void index() {
		
	}
	
	/**
	 * 加载数据
	 * @param name
	 * @param length
	 * @param start
	 * @param draw
	 * @param order
	 * @param columns
	 * @return
	 */
	@At
	@Ok("json:full")
	@RequiresAuthentication
	public Object data(@Param("name") String name,@Param("length") int length, @Param("start") int start, @Param("draw") int draw, @Param("::order") List<DataTableOrder> order, @Param("::columns") List<DataTableColumn> columns) {
		return schoolService.init(length, start, draw,name);
	}
	/**
	 * 新增
	 * @return
	 */
	@At
	@Ok("beetl:/platform/base/school/add.html")
	@RequiresAuthentication
	public Object add() {
		Map<String,Object> map=new HashMap<String,Object>();
		//获取片区
		List<Ud_region> regions=regionService.find();
		map.put("regions", regions);
		return map;
	}
	/**
	 * 新增驾校
	 * @param product
	 * @param req
	 * @return
	 */
	@At
	@Ok("json")
	@RequiresAuthentication
	@SLog(tag = "新增驾校", msg = "驾校名:${args[0].name}")
	public Object addDo(@Param("..") Ud_school school,@Param("areaid") String areaid,HttpServletRequest req) {
		try {
			//设置创建时间
			school.setCreateAt((int)(System.currentTimeMillis()/1000));
			school.setJoin_time((int)(System.currentTimeMillis()/1000));
			//设置创建人
			Subject subject = SecurityUtils.getSubject();
            Sys_user user = (Sys_user) subject.getPrincipal();
            school.setCreateBy(user.getId());
            schoolService.insert(school);
            //设置作用区域
            if(null !=areaid){
            	String []areaids=areaid.split(",");
            	List<Ud_school_area> areas=new ArrayList<Ud_school_area>();
            	for (int i = 0; i < areaids.length; i++) {
            		Ud_school_area area=new Ud_school_area();
            		area.setId(StringUtil.newId32());
            		area.setArea_id(areaids[i]);
            		area.setSchool_id(school.getId());
            		area.setCreateAt((int)(System.currentTimeMillis()/1000));
            		
            		areas.add(area);
				}
            	schoolAreaService.insertList(areas);
            	
            }
	        return Result.success("保存成功");
	    } catch (Exception e) {
	    	return Result.error(e.getMessage());
	    }
	}
	/**
	 * 编辑
	 * @param id
	 * @return
	 */
	@At("/edit/?")
	@Ok("beetl:/platform/base/school/edit.html")
	@RequiresAuthentication
	public Object edit(String id) {
		Map<String,Object> map=new HashMap<String,Object>();
		//组装数据
		List<Ud_region> regions=regionService.find();
		map.put("regions", regions);
		map.put("school", schoolService.fetch(id));
		List<Ud_school_area> areas=schoolAreaService.query(Cnd.where("school_id", "=", id));
		String areasNames="";
		String areasids="";
		for(Ud_school_area area:areas){
			areasNames+=areaService.fetch(area.getArea_id()).getName()+",";
			areasids+=area.getArea_id()+",";
		}
		if(!"".equals(areasids)){
			areasids=areasids.substring(0, areasids.length()-1);
		}
		if(!"".equals(areasNames)){
			areasNames=areasNames.substring(0, areasNames.length()-1);
		}
		map.put("areasNames", areasNames);
		map.put("areasids", areasids);
		return map;
	}
	/**
	 * 修改
	 * @param product
	 * @param req
	 * @return
	 */
	@At
	@Ok("json")
	@RequiresAuthentication
	@SLog(tag = "修改驾校", msg = "驾校名:${args[0].name}")
	public Object editDo(@Param("..")  Ud_school school, @Param("areaid") String areaid,HttpServletRequest req) {
		try {
			school.setOpAt((int)(System.currentTimeMillis()/1000));
			schoolService.updateIgnoreNull(school);
			schoolAreaService.updateAreas(areaid,school.getId());
	   		return Result.success("保存成功");
		} catch (Exception e) {
			return Result.error(e.getMessage());
		}
	}
	/**
	 * 删除
	 * @param id
	 * @param req
	 * @return
	 */
	@At("/delete/?")
    @Ok("json")
	@RequiresAuthentication
    @SLog(tag = "删除驾校", msg = "驾校名:${args[1].getAttribute('name')}")
    public Object delete(String id, HttpServletRequest req) {
        try {
        	Ud_school shop= schoolService.fetch(id);
        	shop.setDelFlag(true);
        	schoolService.updateIgnoreNull(shop);
            req.setAttribute("name", shop.getName());
            return Result.success("删除成功");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
	
	
	/**
	 * 加载区域列表
	 * @param pid
	 * @return
	 */
	@At
	@Ok("json")
	@RequiresAuthentication
	public Object tree(@Param("pid") String pid) {
		List<Map<String, Object>> tree = new ArrayList<>();
		
		List<Ud_area> areList=new ArrayList<Ud_area>();
		if(pid ==null || pid.equals("")){
			areList=areaService.query(Cnd.where("level", "=", 2).asc("city_code"));
		}else{
			areList=areaService.query(Cnd.where("parent_id", "=", Strings.sBlank(pid)).asc("city_code"));
		}
		for (Ud_area area : areList) {
			 Map<String, Object> obj = new HashMap<>();
			obj.put("id", area.getId());
			obj.put("text", area.getName());				
			obj.put("children", areaService.isHasChildren(area.getId()));
			tree.add(obj);
		}
		return tree;
	}

}